package com.example.saveword.save_word;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.saveword.R;
import com.example.saveword.dao.WordRecordDao;
import com.example.saveword.model.User;
import com.example.saveword.utils.JsonUtils;
import com.example.saveword.utils.SPUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Calendar;
import java.util.List;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyFragment extends Fragment implements View.OnClickListener{

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    protected View mView; // 声明一个视图对象
    protected Context mContext; // 上下文对象
    private ImageView iv_avatar;
    private TextView tv_username, tv_userId;
    private TextView tv_studyWords, tv_keepTime;
    private TextView btn_logout;
    // 用户信息
    private User user;
    private String username, qqNumber;
    int id, studyWords, keepTime;
    WordRecordDao wordRecordDao;
    // 折线图
    private LineChartView chart;
    private final int numberOfPoints = 7; // 点的数量
    private ValueShape shape = ValueShape.CIRCLE; // 点为圆形
    private int maxNumber = 0;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WordBookFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyFragment newInstance(String param1, String param2) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getActivity(); // 获取活动页面的上下文
        mView = inflater.inflate(R.layout.fragment_my, container, false);
        wordRecordDao = new WordRecordDao(mContext);
        getUserData();
        init();
        loadImage();

        paintLearningTimeChart();
        resetYViewport();
        // Inflate the layout for this fragment
        return mView;
    }

    private void init() {
        iv_avatar = mView.findViewById(R.id.iv_avatar);
        tv_userId = mView.findViewById(R.id.tv_userId);
        tv_username = mView.findViewById(R.id.tv_username);
        tv_studyWords = mView.findViewById(R.id.tv_studyWords);
        tv_keepTime = mView.findViewById(R.id.tv_keepTime);
        chart = mView.findViewById(R.id.hc_chart);
        btn_logout = mView.findViewById(R.id.btn_logout);
        btn_logout.setOnClickListener(this);

        tv_userId.setText("ID：" + String.valueOf(id));
        tv_username.setText(username);
        tv_studyWords.setText(String.valueOf(studyWords));
        tv_keepTime.setText(String.valueOf(keepTime));
    }

    public void loadImage() {
        String url = "https://q1.qlogo.cn/g?b=qq&nk=" + qqNumber + "&s=100";
        Glide.with(this).load(url).circleCrop().into(iv_avatar);
    }

    public void getUserData() {
        user = (User) JsonUtils.jsonToObject((String) SPUtils.get(mContext, "User", ""), User.class);
        id = user.get_id();
        username = user.getUsername();
        qqNumber = user.getPhone();
        // 获取总共的学习单词量
        studyWords = wordRecordDao.getAllStudyWordNumById(String.valueOf(id));
        // 获取总共的打卡天数
        keepTime = wordRecordDao.getKeepTimeById(String.valueOf(id));
    }

    // 绘制折线图（近七天每天背单词的时长）
    public void paintLearningTimeChart() {
        // 要绘制的线条列表
        List<Line> lines = new ArrayList<Line>();
        // x 轴数据
        List<AxisValue> axisXValues = new ArrayList<AxisValue>();
        // y 轴的对应值
        List<PointValue> values = new ArrayList<PointValue>();
        // 获取每一天的学习时长
        for(int i = 0; i < numberOfPoints; i ++) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            Date date = calendar.getTime();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat mddf = new SimpleDateFormat("MM-dd");
            String now = df.format(date);
            String nowDF = mddf.format(date);
            int len = wordRecordDao.getDAilyLearningTime(String.valueOf(id), now);
            axisXValues.add(i, new AxisValue(i).setLabel(nowDF));
            values.add(new PointValue(i, len));
            maxNumber = Math.max(maxNumber, len);
        }
        maxNumber += 10;
        Line line = new Line(values);
        line.setColor(ChartUtils.pickColor()); // 设置颜色随机
        line.setShape(shape); // 设置形状
        line.setCubic(true); // 设置线为曲线，反之为折线
        line.setFilled(true); // 设置填满
        line.setHasLabels(true); // 显示便签
        line.setHasLabelsOnlyForSelected(true);
        line.setHasLines(true);
        line.setHasPoints(true);
        lines.add(line);

        LineChartData data = new LineChartData(lines);
        data.setAxisXBottom(new Axis(axisXValues).setHasLines(true).setTextColor(Color.BLACK).setName("").setHasTiltedLabels(true).setMaxLabelChars(4));
        data.setAxisYLeft(new Axis().setHasLines(true).setName("").setTextColor(Color.BLACK).setMaxLabelChars(2));
        data.setBaseValue(Float.NEGATIVE_INFINITY);
        chart.setLineChartData(data);
    }

    // 设置 y 轴的值从 0 到 maxNumber
    private void resetYViewport() {
        final Viewport v = new Viewport(chart.getMaximumViewport());
        v.bottom = 0;
        v.top = maxNumber;
        v.left = 0;
        v.right = numberOfPoints - 1;
        chart.setMaximumViewport(v);
        chart.setCurrentViewport(v);
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn_logout) {
            Intent intent = new Intent();
            // 清空任务栈
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClass(mContext, LoginActivity.class);
            startActivity(intent);
        }
    }
}